package com.lkd.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lkd.dto.PartnerDto;
import com.lkd.entity.Partner;
import com.lkd.entity.VendingMachine;
import com.lkd.mapper.PartnerMapper;
import com.lkd.service.IPartnerService;
import com.lkd.service.IVendingMachineService;
import com.lkd.vo.PageBean;
import com.lkd.vo.PartnerInfoVo;
import com.lkd.vo.PartnerVo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 合作商表 服务实现类
 * </p>
 *
 * @author xiaotao
 * @since 2025-10-10
 */
@RequiredArgsConstructor
@Service
public class PartnerServiceImpl extends ServiceImpl<PartnerMapper, Partner> implements IPartnerService {

    private final IVendingMachineService vendingMachineService;

    /**
     * 合作商搜索
     *
     * @param partnerDto
     * @return
     */
    @Override
    public PageBean<PartnerVo> search(PartnerDto partnerDto) {
        //1.设置分页参数
        Page<Partner> partnerPage = new Page<>(partnerDto.getPageIndex(), partnerDto.getPageSize());

        //2.设置业务参数
        LambdaQueryWrapper<Partner> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StrUtil.isNotBlank(partnerDto.getName()), Partner::getName, partnerDto.getName());

        //3.执行分页查询
        Page<Partner> page = this.page(partnerPage, wrapper);

        //3.1需要重新封装，构建PartnerVo
        List<PartnerVo> partnerVoList = page.getRecords().stream().map(partner -> {
            PartnerVo partnerVo = new PartnerVo();
            BeanUtil.copyProperties(partner, partnerVo);
            //需要添加vmCount(该数据从设备表中获取),统计的结果
            Long vmCount = vendingMachineService.lambdaQuery().eq(VendingMachine::getOwnerId, partner.getId())
                    .count();
            partnerVo.setVmCount(vmCount.intValue());
            return partnerVo;
        }).collect(Collectors.toList());

        //4.构建返回结果
        return new PageBean<>((int)page.getCurrent(), (int)page.getSize(), page.getPages(), page.getTotal(), partnerVoList);
    }

    /**
     * 获取合作详情
     *
     * @param id
     * @return
     */
    @Override
    public PartnerInfoVo getPartnerInfo(Integer id) {
        //首先根据id获取合作商信息
        Partner partner = getById(id);
        //属性拷贝到partnerInfoVo中
        PartnerInfoVo partnerInfoVo = new PartnerInfoVo();
        BeanUtil.copyProperties(partner, partnerInfoVo);

        //获取vmCount
        long vmCount = vendingMachineService.lambdaQuery().eq(VendingMachine::getOwnerId, partner.getId())
                .count();
        partnerInfoVo.setVmCount((int) vmCount);

        return partnerInfoVo;
    }

}
